from flask import Flask, request, send_file
import requests
from bs4 import BeautifulSoup
from PIL import Image, ImageDraw, ImageFont
import io

app = Flask(__name__)


@app.route('/generate', methods=['POST'])
def generate_image():
    url = request.json.get('url')
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    # 提取网页内容
    content = soup.get_text()

    # 创建图像
    img = Image.new('RGB', (800, 2000), color=(255, 255, 255))
    d = ImageDraw.Draw(img)
    font = ImageFont.truetype("arial.ttf", 15)
    d.text((10, 10), content, fill=(0, 0, 0), font=font)

    # 保存图像到字节流
    img_byte_arr = io.BytesIO()
    img.save(img_byte_arr, format='PNG')
    img_byte_arr.seek(0)

    return send_file(img_byte_arr, mimetype='image/png')


if __name__ == '__main__':
    app.run(debug=True)
